/**
 * Octopus, an XMMS2 client.
 * Copyright (C) 2014 Octopus Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace Octopus {
	public class XmmsClient : Object {
		private Xmms.Client _xmms_client = null;
		private void*       _gmain      = null;

		public XmmsClient () {}

		public void init () {
			connect_to_xmms ();
			init_main_loop ();
		}

		public Xmms.Client get_xmms () {
			return _xmms_client;
		}

		private void connect_to_xmms () {
			_xmms_client = new Xmms.Client ("octopus");

			string path = GLib.Environment.get_variable ("XMMS_PATH");
			GLib.debug ("XMMS_PATH = %s", path);
			if (!_xmms_client.connect (path)) {
				GLib.debug ("Could not connect: %s", _xmms_client.get_last_error ());
				GLib.debug ("try to launch xmms2...");
				string xmms2_stdout;
				string xmms2_stderr;
				try {
					GLib.Process.spawn_command_line_sync("xmms2-launcher", out xmms2_stdout, out xmms2_stderr, null);
					while (true) {
						GLib.debug ("try to connect to xmms2...");
						if (!_xmms_client.connect (path)) {
							GLib.debug ("Could not connect: %s", _xmms_client.get_last_error ());
						} else {
							break;
						}
						GLib.Thread.usleep(1000000); //wait 1 second and try to connect again
					}
				} catch (GLib.SpawnError e) {
					GLib.warning ("Unable to spawn 'xmms2-launcher' (%s)", e.message);
				}
			}
		}

		private void init_main_loop () {
			_gmain = Xmms.MainLoop.GMain.init(_xmms_client);
		}
	}
}
